#include <iostream>
#include <string>
#include <cstring>
#include <ctime>
#include <cassert>
#include <unistd.h>
#include "Socket.hpp"
#include "Protocol.hpp"

// 客户端：生成随机数据 序列化+编码 发送; 解码+反序列化 读取结果
static void Usage(const std::string &proc)
{
    std::cout << "\nUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

// ./clientcal ip port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    Sock sockfd;
    sockfd.Socket();
    bool connectFlag = sockfd.Connect(serverip, serverport);
    if (!connectFlag)
        return 1;

    srand(time(nullptr) ^ getpid());
    int cnt = 1;
    const std::string opers = "+-*/%&^";

    std::string inbuffer_stream;
    while (cnt <= 5)
    {
        std::cout << "=================第" << cnt << "次测试....., " << "=================" << std::endl;
        int x = rand() % 100 + 1;
        usleep(1234);
        int y = rand() % 100;
        usleep(4321);
        char oper = opers[rand() % opers.size()];
        Request req(x, y, oper);
        req.DebugPrint();

        std::string Serialized_StringMsg;
        req.Serialize(&Serialized_StringMsg);

        Serialized_StringMsg = Encode(Serialized_StringMsg);

        ssize_t bytes_sent = write(sockfd.getSocketFd(), Serialized_StringMsg.c_str(), Serialized_StringMsg.size());
        if (bytes_sent == -1)
        {
            // 处理写入错误
            perror("write failed");
            break;
        }
        else if (bytes_sent == 0)
        {
            // 处理对方关闭连接的情况
            std::cout << "Connection closed by peer" << std::endl;
            break;
        }
        else
        {
            // 成功发送数据
            std::cout << "Sent " << bytes_sent << " bytes." << std::endl;
            std::cout << "============send to server===========" << std::endl;
            std::cout << Serialized_StringMsg;
            std::cout << "============send to server===========" << std::endl;
        }

        char buffer[128];
        ssize_t n = read(sockfd.getSocketFd(), buffer, sizeof(buffer)); // 无法保证能读到一个完整的报文
        if (n == -1)
        {
            // 处理读取错误
            perror("read failed");
            break;
        }
        else if (n == 0)
        {
            // 对方关闭了连接
            std::cout << "Connection closed by peer" << std::endl;
            break;
        }
        else if (n > 0)
        {
            buffer[n] = 0;
            inbuffer_stream += buffer; // "len"\n"result code"\n
            std::cout << "============server send to me===========" << std::endl;
            std::cout << inbuffer_stream;
            std::cout << "============server send to me===========" << std::endl;

            std::string Decoded_StringMsg;
            bool r = Decode(inbuffer_stream, &Decoded_StringMsg); // "result code"
            assert(r);

            Response resp;
            r = resp.Deserialize(Decoded_StringMsg);
            assert(r);

            resp.DebugPrint();
        }

        std::cout << std::endl;
        sleep(1);

        cnt++;
    }

    sockfd.CloseFd();
    return 0;
}